package cn.ccccltd.waf.id_generator.web;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;

import com.alibaba.druid.util.DruidWebUtils;
import com.alibaba.druid.util.PatternMatcher;
import com.alibaba.druid.util.ServletPathMatcher;

import cn.ccccltd.waf.id_generator.constants.Constants;
import cn.ccccltd.waf.id_generator.init.AppInit;
import cn.ccccltd.waf.id_generator.thread.ThreadLocalContext;
import cn.ccccltd.waf.id_generator.util.CommonUtils;
import cn.ccccltd.waf.id_generator.web.user.vo.User;

/**
 * 创建日期:2017年11月13日
 * Title: 权限过滤
 * Description：对本文件的详细描述，原则上不能少于50字
 * @author yangjingjiang
 * @mender：（文件的修改者，文件创建者之外的人）
 * @version 1.0
 * Remark：认为有必要的其他信息
 */
@WebFilter(filterName = "securityFilter", urlPatterns = "/*", 
	initParams={
		//忽略资源
	    @WebInitParam(name="exclusions",value="*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*")
	}
)
@Order(-5)
public class SecurityFilter implements Filter{
	
	private static Logger log = LoggerFactory.getLogger(SecurityFilter.class);
	
    protected String           contextPath;
    
    private Set<String>        excludesPattern;
    
    protected PatternMatcher   pathMatcher                       = new ServletPathMatcher();
    
    public static final String PARAM_NAME_EXCLUSIONS             = "exclusions";
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		
		this.contextPath = DruidWebUtils.getContextPath(filterConfig.getServletContext());
		
        {
            String exclusions = filterConfig.getInitParameter(PARAM_NAME_EXCLUSIONS);
            if (exclusions != null && exclusions.trim().length() != 0) {
                excludesPattern = new HashSet<String>(Arrays.asList(exclusions.split("\\s*,\\s*")));
            }
        }
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		
		String requestURI = httpServletRequest.getRequestURI();
		
        if (isExclusion(requestURI)) {
            chain.doFilter(request, response);
            return;
        }
		
		try {

//			/druid/*
			if(requestURI.endsWith(Constants.SERVER_STARTED)) {
				CommonUtils.writeJsonToPage((HttpServletResponse)response, "主键服务启动成功！");
				return;
			}
			
			log.info("***********过滤器doFilter!*************");
			//判断是否有秘钥
			Object secret = request.getParameter("sendSystemid");
			
			log.info("*************sendSystemid值***********" + secret);
			
			User wafAuthority = (User)AppInit.userMap.get(secret);
			
			log.info("{}当前操作人员{}",Constants.LOG_DEBUG_PREFIX, wafAuthority);
			
//			if (null == wafAuthority) {
//				CommonUtils.writeJsonToPage((HttpServletResponse)response, new ResultData(Constants.FALSE, StateCode.ERR_NOT_PERMISSION, StateCode.ERR_NOT_PERMISSION_MSG));
//				return;
//			}else {
//				ThreadLocalContext.setValue(Constants.SESSION, wafAuthority);
//			}
			
			chain.doFilter(request, response);
		} finally {
			//处理threadlocal中的值在线程之间传递的处理
			ThreadLocalContext.remove();
        }  
		
		
	}

	/**
	 * 功能: 正则匹配不需要过滤的地址<br>
	 * 作者: yangjingjiang <br>
	 * 创建日期:2018年3月30日 <br>
	 * 修改者: mender <br>
	 * 修改日期: modifydate <br>
	 * @param requestURI
	 * @return
	 */
    public boolean isExclusion(String requestURI) {
        if (excludesPattern == null) {
            return false;
        }

        if (contextPath != null && requestURI.startsWith(contextPath)) {
            requestURI = requestURI.substring(contextPath.length());
            if (!requestURI.startsWith("/")) {
                requestURI = "/" + requestURI;
            }
        }

        for (String pattern : excludesPattern) {
            if (pathMatcher.matches(pattern, requestURI)) {
                return true;
            }
        }

        return false;
    }
	
	@Override
	public void destroy() {
		 
	}

}
